package com.abel.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.UUID;

/**
 * 日志追踪拦截器
 *
 * @author heyangyang
 * @since 2024-05-16
 */

public class LogInterceptor implements HandlerInterceptor {

    public static final String TRACE_ID = "TRACE_ID";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String traceId = request.getHeader(TRACE_ID);
        //可以考虑让客户端传入链路ID，但需保证一定的复杂度唯一性；如果没使用默认UUID自动生成
        if (traceId != null) {
            request.setAttribute(TRACE_ID, traceId);
        }
        MDC.put(TRACE_ID, UUID.randomUUID().toString().replaceAll("-", ""));
        return true;
    }

    @Override

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.remove(TRACE_ID);
    }

}
